package org.hao.samples.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hao.samples.dao.IExamScoreDAO;
import org.hao.samples.dao.IExam_testDAO;
import org.hao.samples.model.ExamScore;
import org.hao.samples.model.ExamTestType;
import org.hao.samples.model.ExamTestVO;
import org.hao.samples.model.Exam_test;
import org.hao.samples.model.PagerModel;
import org.hao.samples.model.StudentVO;
import org.hao.samples.model.Subject;
import org.hao.samples.model.testVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ExamTestServiceImpl implements ExamTestService {
	@Autowired
	private IExam_testDAO dao;
	
	@Autowired
	private IExamScoreDAO scoredao;
	
	private ExamScore examScore;

	@Override
	public List<Exam_test> findAllExamTest() {
		return dao.findAllExam_test();
	}

	@Override
	public PagerModel<ExamTestVO> findAllByPage() {
		return dao.findAllByPage();
	}

	@Override
	public void deleteExamTest(Integer id) throws Exception {
		dao.delete(id);
	}

	@Override
	public Exam_test getExamTestById(Integer id) {
		return dao.getExam_testById(id);
	}

	@Override
	public ExamTestVO getTestById(Integer id) {
		Exam_test entity = dao.getExam_testById(id);
		if (entity != null) {
			ExamTestVO vo = new ExamTestVO();
			BeanUtils.copyProperties(entity, vo);

			vo.setSubId(entity.getSubject().getSub_id());
			vo.setSubName(entity.getSubject().getName());

			vo.setTestTypeId(entity.getExamTestType().getId());
			vo.setTestType(entity.getExamTestType().getTestType());
			vo.setTestTypeScore(entity.getExamTestType().getTestTypeScore());
			return vo;
		}
		return null;
	}

	@Override
	public ExamTestVO saveExamTest(ExamTestVO examTestVO) throws Exception {
		Exam_test entity = new Exam_test();
		BeanUtils.copyProperties(examTestVO, entity);

		Subject subject = new Subject();
		subject.setSub_id(examTestVO.getSubId());
		entity.setSubject(subject);

		ExamTestType examTestType = new ExamTestType();
		examTestType.setId(examTestVO.getTestTypeId());
		entity.setExamTestType(examTestType);

		dao.createExam_test(entity);
		return null;
	}

	@Override
	public void editTest(ExamTestVO examTestVO) throws Exception {
		Exam_test entity = new Exam_test();
		BeanUtils.copyProperties(examTestVO, entity);

		Subject subject = new Subject();
		subject.setSub_id(examTestVO.getSubId());
		entity.setSubject(subject);

		ExamTestType examTestType = new ExamTestType();
		examTestType.setId(examTestVO.getTestTypeId());
		entity.setExamTestType(examTestType);

		dao.editExam_test(entity);
	}

	@Override
	public List<testVO> findExamTestBySubIdTypeId(Integer subId, Integer userId) {
		
		List<testVO> testVOList = new ArrayList<testVO>();
		
		//判断当前学生是不是已经进入过考试，数据库是不是已经随机生成他的试卷，如果是就不再新随机生成考题
		List<ExamScore> oldTest = scoredao.findExamScoreBystuIdAndsubId(userId, subId);
		if(!oldTest.isEmpty()){
			List<String> result = Arrays.asList(oldTest.get(0).getTestId().split(","));
			for (String i : result) {
				int j = Integer.parseInt(i);
				testVO vo = new testVO();
				BeanUtils.copyProperties(dao.getExam_testById(j), vo);
				testVOList.add(vo);
			}
			this.examScore = oldTest.get(0); 
			return testVOList;
		}
		
		// 第一次进入考试，随机获取当前科目的单选题
		List<Exam_test> list = dao.findExamTestBySubIdTypeId(subId, 1);
		int[] random = this.randomCommon(0, list.size(), 5);

		for (int i : random) {
			testVO vo = new testVO();
			BeanUtils.copyProperties(list.get(i), vo);
			testVOList.add(vo);
		}

		// 在exam_score表中增加一条数据
		String testId = "";
		for (testVO l : testVOList) {
			testId += l.getId();
			testId += ",";
		}
		testId = testId.substring(0, testId.length()-1);
		
		ExamScore test = new ExamScore();
		Subject subject = new Subject();
		subject.setSub_id(subId);
		//考试结束时间
		Date currentTime = null;
		Calendar currentTimecalendar = Calendar.getInstance();
		currentTimecalendar.setTime(new Date());
		currentTimecalendar.add(Calendar.MINUTE, list.get(0).getSubject().getTotal_time());
		currentTime = currentTimecalendar.getTime();
		test.setExamTime(currentTime);
		
		test.setSubject(subject);
		test.setUserId(userId);
		test.setTestId(testId);
		scoredao.addExamScore(test);
		
		//把刚才新增数据赋给examScore
		this.examScore = scoredao.findExamScoreBystuIdAndsubId(userId, subId).get(0);
		return testVOList;
	}


	// 改试卷
	@Override
	public Map<String, Object> checkAnswer(String answerString) {
		
		HashMap<String, Object> resulMap = new HashMap<String, Object>();
		// 题正确的数量
		Integer count = 0;
		// 得分
		Double score = 0.0;

		if (!answerString.isEmpty()) {

			// 把"45B,44D,44A"这样的字符串拆开，数字指题的ID，字母指学生选的答案
			List<String> result = Arrays.asList(answerString.split(","));

			for (String an : result) {
				Integer testId = Integer.parseInt(an.substring(0, an.length() - 1));
				String answer = an.substring(an.length() - 1);
				Exam_test test = dao.getExam_testById(testId);
				if (answer.equals(test.getAnswer())) {
					count++;
					score = score + test.getExamTestType().getTestTypeScore();
				}

			}
		}
		
		//把分数写进数据库
		ExamScore test = new ExamScore();
		test = this.examScore;
		test.setScore(score);
		scoredao.editExamScore(test);
		
		resulMap.put("count", count);
		resulMap.put("score", score);
		return resulMap;
	}
	
	/**
	 * 随机指定范围内N个不重复的数 最简单最基本的方法
	 * 
	 * @param min
	 *            指定范围最小值
	 * @param max
	 *            指定范围最大值
	 * @param n
	 *            随机数个数
	 */
	public int[] randomCommon(int min, int max, int n) {
		if (n > (max - min + 1) || max < min) {
			return null;
		}
		int[] result = new int[n];
		int count = 0;
		while (count < n) {
			int num = (int) (Math.random() * (max - min)) + min;
			boolean flag = true;
			for (int j = 0; j < n; j++) {
				if (num == result[j]) {
					flag = false;
					break;
				}
			}
			if (flag) {
				result[count] = num;
				count++;
			}
		}
		return result;
	}

	@Override
	public Integer getoutTime(Integer subId, Integer userId) {
		List<ExamScore> test = scoredao.findExamScoreBystuIdAndsubId(userId, subId);
		Calendar nowTime=Calendar.getInstance(),stopTime=Calendar.getInstance();
		nowTime.setTime(new Date());	//设置为当前系统时间 
		stopTime.setTime(test.get(0).getExamTime());	//设置为结束时间
		
		long nowTime1=nowTime.getTimeInMillis();
		long stopTime1=stopTime.getTimeInMillis();
		long second=(stopTime1-nowTime1)/(1000);//转化second
		System.out.println(second);

		return (int) second;
	}

	@Override
	public List<ExamScore> teacherChexkScore(Integer subId,Integer stuId) {
		// TODO Auto-generated method stub
		return scoredao.findExamScoreBystuIdAndsubId(stuId, subId);
	}
}
